package com.gange.exceptionhandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gange.exception.IllTokenException;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    //当异常发生的时候会自动运行该方法。
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //我们响应的是一个json串
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //响应的状态码
        if(e instanceof IllTokenException){
            httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        }else{
            httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        //当发生异常的时候提示什么错误信息
        String message = e.getMessage();//异常信息
        Map<String,String> map=new HashMap<>();
        map.put("msg",message);
        //json的工具类。
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(httpServletResponse.getWriter(),map);
        return new ModelAndView();
    }
}
